package models

import (
	_ "github.com/Go-SQL-Driver/MySQL"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/mattn/go-oci8"
	_ "github.com/mattn/go-sqlite3"
	"job-scheduler/controllers"
)

func RegisterDataBase() error {
	_ = orm.RegisterDriver("sqlite3", orm.DRSqlite)

	_ = orm.RegisterDataBase("default",
		"sqlite3",
		"./database/cron.db",
		beego.AppConfig.DefaultInt("MaxLocalIdleConn", 1),
		beego.AppConfig.DefaultInt("MaxLocalOpenConn", 2))

	if beego.AppConfig.DefaultString("oracle.switch", "off") == "on" {
		_ = orm.RegisterDriver("oci8", orm.DROracle)

		_ = orm.RegisterDataBase("oracle",
			beego.AppConfig.DefaultString("oracle.driver", "oci8"),
			beego.AppConfig.String("oracle.connection"),
			beego.AppConfig.DefaultInt("oracle.maxIdleConn", 1),
			beego.AppConfig.DefaultInt("oracle.maxOpenConn", 2))
	}

	if beego.AppConfig.DefaultString("mysql.switch", "off") == "on" {
		_ = orm.RegisterDriver("mysql", orm.DRMySQL)

		_ = orm.RegisterDataBase("mysql",
			beego.AppConfig.DefaultString("mysql.driver", "mysql"),
			beego.AppConfig.String("mysql.connection"),
			beego.AppConfig.DefaultInt("mysql.maxIdleConn", 1),
			beego.AppConfig.DefaultInt("mysql.maxOpenConn", 2))
	}

	orm.RegisterModel(&controllers.TblJobCtl{}, &controllers.TblJobDtl{})

	orm.BootStrap()

	orm.DebugLog = orm.NewLog(logs.GetBeeLogger())

	if beego.AppConfig.DefaultBool("databaseLogSwitch", false) {
		orm.Debug = true
	}

	return nil
}
